const router = require('koa-router')();  //注意：引入的方式
const db = require('../utils/database.js')

router.prefix('/staff')

router.get('/', ctx => {
    ctx.body = "staff--index";
})


// 查询 分页 搜索 排序
router.get('/list', async ctx => {
    const { order, by, page = 0, pageSize = 20, query, query1 } = ctx.request.query // request可省略
    let sort = {}, where = {}
    if (by) {
        sort[by] = order // by是条件 order是-1或1
    }
    if (query) { // 员工姓名
        where.name = { $regex: new RegExp(query) }
    }
    if (query1) { // 员工岗位
        where.post = { $regex: new RegExp(query1) }
    }
    //总条数
    const total = await db.total('staff', where)
    const data = await db.find('staff', { where, sort, skip: page * pageSize, limit: pageSize })
    ctx.body = { success: true, code: 20000, message: "数据查询成功", data, total }
})

// 新增
router.post('/save', async ctx => {
    const { name, post, id, cipher, role, on } = ctx.request.body;
    const data = await db.insert('staff', { name, post, id, cipher, role, on, time: Date.now() })
    ctx.body = { success: true, code: 20000, message: "数据新增成功", data }
})

// 修改
router.post('/modify', async ctx => {
    const { _id, name, post, id, cipher, role, on } = ctx.request.body
    const data = await db.update('staff', { _id }, { name, post, id, cipher, role, on, time: Date.now() })
    ctx.body = { success: true, code: 20000, message: "数据修改成功", data }
})

// 删除
router.get('/delete', async ctx => {
    const { _id } = ctx.request.query
    const data = await db.delete('staff', { _id })
    ctx.body = { success: true, code: 20000, message: "数据删除成功", data }
})


module.exports = router
